<template>
  <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" :width="width"
             :append-to-body="true" @open="beforeOpen" @closed="afterClose">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" size="small"
             :disabled="submitLoading || queryLoading || type === 'show'">
      <el-row :gutter="16">
        <el-col :span="6">
          <el-form-item label="商品编号" prop="id">
            <el-input type="text" v-model="form.id" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品名称" prop="name">
            <el-input type="text" v-model="form.name" placeholder="商品名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品类别" prop="goodCategoryId">
            <el-cascader v-model="form.goodCategoryId" :options="categoryList" :show-all-levels="false"
                         :props="categoryCascaderProps" :disabled="categoryLoading ? true : null"
                         :placeholder="categoryLoading ? '加载中...' : '请选择'" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品分组" prop="groupId">
            <el-cascader v-model="form.groupId" :options="groupList" :show-all-levels="false"
                         :props="groupCascaderProps" :disabled="groupLoading ? true : null"
                         :placeholder="groupLoading ? '加载中...' : '请选择'"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品卖点" prop="sellPoint">
            <el-input type="text" v-model="form.sellPoint" placeholder="卖点"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品运费" prop="freight">
            <el-input-number v-model="form.freight" :min="0" :precision="2"
                             controls-position="right" placeholder="运费，单位元"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="简要描述" prop="simpleDesc">
            <el-input type="text" v-model="form.simpleDesc" placeholder="简要描述"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="详细描述" prop="description">
            <el-input type="text" v-model="form.description" placeholder="详细描述"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="remark">
            <el-input type="text" v-model="form.remark" placeholder="备注"/>
          </el-form-item>
        </el-col>
      </el-row>
      <part-image-selector :file-list="fileList" ref="selector" width="100%" box-width="40px" box-height="80px" />
      <template v-for="(item, index) in form.subGoodList">
        <el-row :gutter="10" :key="index">
          <el-col :span="6">
            <el-form-item label="名称" :prop="'subGoodList.' + index + '.subGoodName'"
                          :rules="rules.sub.subGoodName">
              <el-input type="text" v-model="item.subGoodName" placeholder="商品名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="数量" :prop="'subGoodList.' + index + '.count'"
                          :rules="rules.sub.count">
              <el-input-number v-model="item.count" :min="0" :precision="0"
                               controls-position="right" placeholder="商品数量"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="价格" :prop="'subGoodList.' + index + '.price'"
                          :rules="rules.sub.price">
              <el-input-number v-model="item.price" :min="0"
                               :precision="2" controls-position="right" placeholder="商品价格，单位元" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备注" :prop="'subGoodList.' + index + '.remark'"
                          :rules="rules.sub.remark">
              <el-input type="text" v-model="item.remark" placeholder="备注"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="描述" :prop="'subGoodList.' + index + '.description'"
                          :rules="rules.sub.description">
              <el-input type="text" v-model="item.description" placeholder="详细描述"/>
            </el-form-item>
          </el-col>
          <!--suppress HtmlDeprecatedAttribute -->
          <el-col :span="12" align="right">
            <el-button type="info" icon="el-icon-minus" @click="removeSubItem(item, index)"
                v-if="visibleSubItemRemove" size="small">移除
            </el-button>
            <el-button type="primary" icon="el-icon-plus" @click="addSubItem" size="small">添加一列
            </el-button>
          </el-col>
        </el-row>
      </template>
    </el-form>
    <span slot="footer">
      <el-button @click="closeDialog" size="small">取消</el-button>
      <el-button v-if="type === 'show'" @click="toEdit" :disabled="queryLoading" size="small">编辑</el-button>
      <el-button v-if="type === 'edit'" @click="resetDialog" :loading="queryLoading" icon="el-icon-refresh"
                 :disabled="queryLoading || submitLoading" size="small">刷新</el-button>
      <el-button v-if="type === 'add' || type === 'edit'" @click="handleValidateData" size="small">校验</el-button>
      <el-button v-if="type === 'edit'" type="primary" @click="handleUpdateGood" size="small"
                 :disabled="queryLoading || submitLoading" :loading="submitLoading">提交修改</el-button>
      <el-button v-if="type === 'add'" type="primary" @click="handleAddGoods"
                 :loading="submitLoading" size="small">添加</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { queryGoodCategoryTree } from '@/api/ApiSysGoodCategory'
import { queryGoodGroupTree } from '@/api/ApiGoodGroup'
import PartImageSelector from '@pages/goods/part/pageGoodsList/PartImageSelector'
import { addGood, changeGood } from '@/api/ApiGoods'
import GoodsInsertDTO from '@/api/entity/GoodsInsertDTO'
import SubGoodInsertDTO from '@/api/entity/SubGoodInsertDTO'
import { queryGoodDetailByIdStore } from '@/api/ApiGoodDetail'
import { ResultCode } from '@/constants/constants'
import GoodsChangeDTO from '@/api/entity/GoodsChangeDTO'
import SubGoodChangeDTO from '@/api/entity/SubGoodChangeDTO'

// noinspection JSUnusedGlobalSymbols
export default {
  name: 'PartAddGoodsDialog',
  components: { PartImageSelector },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    width: {
      require: false,
      type: String,
      default: '80%'
    },
    type: {
      require: true,
      type: String
    },
    id: {
      require: false,
      type: [String, Number],
      default: 0
    }
  },
  model: {
    prop: 'dialogVisible',
    event: 'change'
  },
  data () {
    return {
      groupCascaderProps: {
        checkStrictly: true,
        expandTrigger: 'click',
        value: 'id',
        label: 'name',
        children: 'children',
        emitPath: false
      },
      categoryCascaderProps: {
        expandTrigger: 'click',
        value: 'id',
        label: 'name',
        children: 'children',
        emitPath: false
      },
      form: this.initDialogData(),
      rules: {
        name: [
          { required: true, message: '商品名称不能为空', trigger: 'blur' }
        ],
        goodCategoryId: [
          { required: true, message: '商品类别不能为空', trigger: ['blur', 'change'] }
        ],
        groupId: [
          { required: true, message: '商品分组不能为空', trigger: ['blur', 'change'] }
        ],
        sellPoint: [
          { required: true, message: '商品买点信息不能为空', trigger: 'blur' }
        ],
        freight: [
          { required: true, message: '商品运费不能为空', trigger: ['blur', 'change'] }
        ],
        simpleDesc: [
          { required: true, message: '商品简要描述不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '商品描述不能为空', trigger: 'blur' }
        ],
        sub: {
          subGoodName: [
            { required: true, message: '商品类别名称不能为空', trigger: 'blur' }
          ],
          count: [
            { required: true, message: '商品数量不能为空', trigger: ['blur', 'change'] }
          ],
          price: [
            { required: true, message: '商品类别价格不能为空', trigger: ['blur', 'change'] }
          ],
          remark: [],
          description: []
        }
      },
      removeSubGoodIds: [],
      categoryLoading: true,
      categoryList: [],
      groupLoading: true,
      groupList: [],
      submitLoading: false,
      fileList: [],
      queryLoading: false
    }
  },
  computed: {
    visibleSubItemRemove () {
      return this.form.subGoodList.length > 1
    },
    dialogTitle () {
      switch (this.type) {
        case 'show':
          return '商品详情'
        case 'edit':
          return '编辑商品'
        case 'add':
          return '添加商品'
      }
      return ''
    }
  },
  methods: {
    closeDialog () {
      this.dialogVisible = false
    },
    dealWithCategory (node) {
      if (node) {
        Object.assign(node, node.node)
        if (node.children) {
          node.children.forEach(this.dealWithCategory)
        }
      }
    },
    initDialog () {
      this.removeSubGoodIds = []
      this.removeSubGoodIds = []
      this.fileList = []
      if (this.$refs.selector) {
        this.$refs.selector.fresh()
      }
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },
    initDialogData () {
      return {
        subGoodList: [{}]
      }
    },
    /**
     * 用于转换数据
     * @param data 源数据
     * @return {*} 转换后的数据
     */
    convertGoodDetailToFormData (data) {
      if (!data.subGoodList || data.subGoodList.length <= 0) {
        data.subGoodList = [{}]
      }
      return data
    },
    convertGoodDetailToFileList (data) {
      const list = []
      if (data && data['goodPictureList']) {
        const images = data['goodPictureList']
        if (typeof images === 'object') {
          images.forEach(item => {
            if (item.id && item.image) {
              list.push({
                url: item.image,
                name: '',
                id: item.id
              })
            }
          })
        }
      }
      return list
    },
    queryGoodDetailToDialog () {
      this.queryLoading = true
      queryGoodDetailByIdStore(this.id, data => {
        if (data && data.code === ResultCode.OK) {
          this.form = this.convertGoodDetailToFormData(data.object)
          this.fileList = this.convertGoodDetailToFileList(data.object)
          this.$refs.selector.fresh()
        }
      }, () => {
        this.queryLoading = false
      })
    },
    beforeOpen () {
      this.initDialog()
      // 添加商品数据
      switch (this.type) {
        case 'add':
          this.form = this.initDialogData()
          break
        case 'show':
          this.form = this.initDialogData()
          this.queryGoodDetailToDialog()
          break
        case 'edit':
          this.form = this.initDialogData()
          this.queryGoodDetailToDialog()
          break
        default:
      }
    },
    afterClose () {
      this.form = this.initDialogData()
      this.fileList = []
    },
    addSubItem () {
      this.form.subGoodList.push({})
    },
    removeSubItem (item, index) {
      if (item && item.id) {
        for (let i = 0; i < this.removeSubGoodIds.length; i++) {
          if (item.id === this.removeSubGoodIds[i]) {
            break
          }
        }
        this.removeSubGoodIds.push(item.id)
      }
      if (this.form.subGoodList.length > 1) {
        this.form.subGoodList.splice(index, 1)
      } else {
        this.$message.error('至少包含一个子商品')
      }
    },
    resetDialog () {
      if (this.type === 'show' || this.type === 'edit') {
        this.queryGoodDetailToDialog()
      }
    },
    handleAddGoods () {
      const vm = this
      this.$refs.form.validate((success) => {
        if (success) {
          const goodsInsertDTO = GoodsInsertDTO.instance()
          Object.assign(goodsInsertDTO, this.form)
          const subList = []
          this.form.subGoodList.forEach(item => {
            subList.push(Object.assign(SubGoodInsertDTO.instance(), item))
          })
          goodsInsertDTO.setSubGoodList(subList)
          this.submitLoading = true
          addGood(goodsInsertDTO, this.$refs.selector.getAddFileList(), () => {
            this.$message.success('添加商品数据成功')
            vm.$emit('update')
          }, () => {
            this.submitLoading = false
          })
        }
      })
    },
    /**
     * 校验数据
     */
    handleValidateData () {
      this.$refs.form.validate((success) => {
        if (success) {
          this.$message.success('校验成功')
        } else {
          this.$message.error('校验失败')
        }
      })
    },
    handleUpdateGood () {
      const vm = this
      this.$refs.form.validate((success) => {
        if (success) {
          this.submitLoading = true
          const goodsChangeDTO = GoodsChangeDTO.instance()
          Object.assign(goodsChangeDTO, this.form)
          // 添加的文件
          const addFiles = this.$refs.selector.getAddFileList()
          // 需要移除的文件
          const removeFiles = this.$refs.selector.getRemoveFileList()
          const removeFilesIds = []
          if (removeFiles && typeof removeFiles === 'object') {
            removeFiles.forEach(item => {
              removeFilesIds.push(item.id)
            })
          }
          goodsChangeDTO.setRemoveFiles(removeFilesIds)
          // 需要移除的子商品
          const removeSubGoods = this.removeSubGoodIds
          goodsChangeDTO.setRemoveSubGoods(removeSubGoods)
          // 需要添加或者修改的子商品
          const subList = []
          this.form.subGoodList.forEach(item => {
            subList.push(Object.assign(SubGoodChangeDTO.instance(), item))
          })
          goodsChangeDTO.setSubGoodList(subList)
          changeGood(goodsChangeDTO, addFiles, data => {
            if (data && data.code === ResultCode.OK) {
              vm.$message.success('更新成功')
              vm.$emit('update')
            }
          }, () => {
            this.submitLoading = false
          })
        }
      })
    },
    toEdit () {
      this.type = 'edit'
    }
  },
  watch: {
    dialogVisible (value) {
      this.$emit('change', value)
    }
  },
  mounted () {
    // 查询类别树
    queryGoodCategoryTree(data => {
      const rootList = data.object.children
      rootList.forEach(this.dealWithCategory)
      this.categoryList = rootList
    }, () => {
      this.categoryLoading = false
    })
    // 查询店铺分组树
    queryGoodGroupTree(data => {
      const rootList = data.object.children
      rootList.forEach(this.dealWithCategory)
      this.groupList = rootList
    }, () => {
      this.groupLoading = false
    })
  }
}
</script>

<style scoped>

</style>
